/*******************************************************************************
 * Copyright (c) 2014 Francesco Gabbrielli
 * 
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Francesco Gabbrielli - initial API and implementation
 ******************************************************************************/
package it.francescogabbrielli.android.solidalapp.home;

import it.francescogabbrielli.android.solidalapp.BaseFragment;
import it.francescogabbrielli.android.solidalapp.Constants;
import it.francescogabbrielli.android.solidalapp.DataEvent;
import it.francescogabbrielli.android.solidalapp.R;
import it.francescogabbrielli.android.solidalapp.SolidalApp;
import it.francescogabbrielli.android.solidalapp.SolidalApp.DataKey;
import it.francescogabbrielli.android.solidalapp.StatusEvent;
import it.francescogabbrielli.android.solidalapp.requestendpoint.model.Request;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

/**
 * 
 */
public class RequestDataFragment extends BaseFragment<HomeFragmentListener>
								implements View.OnClickListener, OnEditorActionListener, OnSeekBarChangeListener {
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_request_data, container, false);
	}
	
	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {

		super.onViewCreated(view, savedInstanceState);
				
//		// check rating bar
		SeekBar bar = (SeekBar) view.findViewById(R.id.request_credits_bar);
		bar.setOnSeekBarChangeListener(this);
		onProgressChanged(bar, bar.getProgress(), false);
//		if(savedInstanceState!=null)
//			bar.setProgress(savedInstanceState.getInt("credits"));
	
		
		EditText detailsEdit = (EditText) getView().findViewById(R.id.request_details_edit);
		detailsEdit.setOnEditorActionListener(this);
		
		// populate duration spinner
		Spinner spinner = (Spinner) view.findViewById(R.id.request_duration_spinner);
		//XXX: provvisorio
		DurationItem[] items = new DurationItem[] {
				new DurationItem(5, "5 min."),
				new DurationItem(30, "30 min."),
				new DurationItem(60, "1 ora"),
				new DurationItem(180, "3 ore"),
				new DurationItem(720, "12 ore"),
				new DurationItem(1440, "1 giorno")
		};
		ArrayAdapter<DurationItem> adapter = new ArrayAdapter<DurationItem>(
				view.getContext(),
				android.R.layout.simple_spinner_item,
				items);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		
		// add button listener
		Button button = (Button) view.findViewById(R.id.request_button);
		button.setOnClickListener(this);

	}
	
	@Override
	public void onStart() {
		super.onStart();
	}
	
	private void updateRequest() {
		
		boolean resetData = false;
		Request request = (Request) app.getData(DataKey.REQUEST);
		boolean enabled = request==null || request.getExpired();
		
		View view = getView();
		if(view!=null) {
			
			SharedPreferences prefs = getActivity().getSharedPreferences(SolidalApp.class.getCanonicalName(), Context.MODE_PRIVATE);
			if (prefs.getBoolean(Constants.RESET_REQUEST, false)) {
				resetData = true;
				prefs.edit().putBoolean(Constants.RESET_REQUEST, false).commit();
			}
			
			EditText text = (EditText) view.findViewById(R.id.request_text_edit);
			text.setEnabled(enabled);
			text.setOnEditorActionListener(new OnEditorActionListener() {
				@Override
				public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
					if (actionId==EditorInfo.IME_ACTION_NEXT) {
						InputMethodManager inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
						inputManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
					}
					return true;
				}
			});
				
			SeekBar bar = (SeekBar) view.findViewById(R.id.request_credits_bar);
			bar.setEnabled(enabled);

			Spinner spinner = (Spinner) view.findViewById(R.id.request_duration_spinner);
			spinner.setEnabled(enabled);
			
			EditText detailsEdit = (EditText) view.findViewById(R.id.request_details_edit);
			if(detailsEdit!=null) 
				detailsEdit.setEnabled(enabled);
			
			// clear fields
			if (resetData) {
				text.setText("");
				bar.setProgress(5);
				spinner.setSelection(0);
				detailsEdit.setText((String) app.getData(DataKey.ADDRESS_TEXT));
			}
			
			// fill in request fields
			if (!enabled) {
				text.setText(request.getMessage());
				bar.setProgress(request.getCredits());
				for (int i=0; i<spinner.getCount(); i++)
					if (((DurationItem) spinner.getItemAtPosition(i)).minutes == request.getDuration()) {
						spinner.setSelection(i);
						break;
					}
				detailsEdit.setText(request.getDetails());
			}
			
			Button button = (Button) view.findViewById(R.id.request_button);
			button.setEnabled(enabled);
		}
	}
	
//	@Override
//	public void onSaveInstanceState(Bundle outState) {
//		View view = getView();
//		if(view!=null)
//			try {
//				SeekBar bar = (SeekBar) view.findViewById(R.id.request_credits_bar);
//				outState.putInt("credits", (int) bar.getRating());
//			} catch(Exception e) {
//				Log.e(SolidalApp.TAG, "Error saving state", e);
//			}
//		super.onSaveInstanceState(outState);
//	}
	
	@Override
	public void onClick(View v) {
		
		// build the request
		try {
			
			View view = getView();
			
			final Request request = new Request();
							
			// message
			EditText requestEdit = (EditText) view.findViewById(R.id.request_text_edit);
			request.setMessage(
//						URLEncoder.encode(
							requestEdit.getEditableText().toString()
//						,"UTF-8")
			);
			
			// credits
			SeekBar creditsBar = (SeekBar) view.findViewById(R.id.request_credits_bar);
			request.setCredits(creditsBar.getProgress());
			
			// duration
			Spinner durationSpinner = (Spinner) view.findViewById(R.id.request_duration_spinner);
			request.setDuration(((DurationItem) durationSpinner.getSelectedItem()).minutes);
			
			// details
			EditText detailsEdit = (EditText) view.findViewById(R.id.request_details_edit);
			request.setDetails(
//						URLEncoder.encode(
							detailsEdit.getText().toString()
//						,"UTF-8")
			);
			
			interactionListener.send(request);
			
		} catch(Exception e) {
			
			Toast.makeText(getActivity(), "Error: "+e, Toast.LENGTH_SHORT).show();
			Log.e(SolidalApp.TAG, e.getMessage(), e);
			
		}

	}
	
	@Override
	public void onStatusUpdate(StatusEvent event) {
		
		switch (event.getType()) {
		case GCM:
			updateRequest();
			break;

		default:
			break;
		}
		
	}
			
	@Override
	public void onDataChanged(DataEvent event) {
		
		DataKey key = event.getKey();
		
		switch(key) {

		case ADDRESS_TEXT:
			String address = (String) app.getData(key);
			EditText detailsEdit = (EditText) getView().findViewById(R.id.request_details_edit);
			if (detailsEdit!=null)
				if (app.getData(DataKey.ADDRESS_TEXT_MANUAL)==null)
					detailsEdit.setText(address);
			break;
			
		case REQUEST:
			updateRequest();
			break;
		
		default:
		}
	}

	@Override
	public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
		if (!view.getText().equals(app.getData(DataKey.ADDRESS_TEXT))) {
			app.setData(DataKey.ADDRESS_TEXT_MANUAL, true);
			app.alert("Manual address");
		}
		if (actionId==EditorInfo.IME_ACTION_SEND)
			onClick(view);
		return true;
	}

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
		TextView tv = (TextView) getView().findViewById(R.id.request_credits_text);
		tv.setText(String.valueOf(progress));
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
	}

}
